package org.lboot.idmo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.idmo.app.AuthApp;
import org.lboot.idmo.app.AuthAppService;
import org.lboot.idmo.app.params.AppQueryParams;
import org.lboot.idmo.app.params.AuthAppCreateParams;
import org.lboot.idmo.app.params.AuthAppUpdateParams;
import org.lboot.idmo.app.router.AuthAppRoute;
import org.lboot.idmo.app.router.AuthAppRouteService;
import org.lboot.idmo.app.router.params.AppRouteCreateParams;
import org.lboot.idmo.app.router.params.AppRouteUpdateParams;
import org.lboot.jpa.utils.JpaDataUtil;
import org.lboot.llog.anno.ApiLog;
import org.lboot.llog.anno.ReqFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("idm")
@AllArgsConstructor
@Api(tags = "授权应用管理")
public class AuthAppController {
    AuthAppService appService;

    AuthAppRouteService routeService;

    @Resource
    ApplicationContext context;

    @ApiLog("应用管理")
    @PostMapping("apps")
    @ApiOperation(value = "应用新建")
    public ResponseDTO<Object> dataCreate(@Validated @RequestBody AuthAppCreateParams params){
        AuthApp authApp = new AuthApp();
        BeanUtil.copyProperties(params, authApp, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        // 获取参数
        String appId = params.getAppId();
        String appName = params.getAppName();
        // 判断是否重复
        List<AuthApp> apps = appService.getByAppIdOrAppName(appId, appName);
        boolean existAppId = false;
        boolean existAppName = false;
        for (AuthApp app:apps){
            if (app.getAppId().equals(appId)){
                existAppId = true;
            }
            if (app.getAppName().equals(appName)){
                existAppName = true;
            }
        }
        if (existAppId){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,"存在重复应用标识");
        }
        if (existAppName){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,"存在重复应用名称");
        }
        return ResponseDTO.succData(
                appService.saveOne(authApp)
        );
    }


    @ApiLog("应用管理")
    @PutMapping("apps")
    @ApiOperation(value = "应用更新")
    public ResponseDTO<Object> dataUpdate(@Validated @RequestBody AuthAppUpdateParams params){
        String id = params.getId();
        AuthApp authApp = appService.getOneUnwrap(id);
        BeanUtil.copyProperties(params, authApp, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return ResponseDTO.succData(
                appService.updateOne(authApp)
        );
    }


    @ReqFilter
    @ApiLog("应用管理")
    @DeleteMapping("apps/{id}")
    @ApiOperation(value = "应用删除")
    public ResponseDTO<Object> dataDelete(@PathVariable("id") String id){
        appService.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }

    @GetMapping("apps/{id}")
    @ApiOperation(value = "应用查询")
    public ResponseDTO<Object> dataQuery(@PathVariable("id") String id){
        return ResponseDTO.succData(
                appService.getOne(id)
        );
    }

    @GetMapping("apps")
    @ApiOperation(value = "应用列表")
    public ResponseDTO<Object> dataList(AppQueryParams params){
        // tips : 页码对应 - 1
        Pageable pageable = JpaDataUtil.buildPageable(params);
        return ResponseDTO.succData(appService.getAll(pageable));
    }

    @PostMapping("apps/{id}/routes")
    @ApiOperation(value = "应用路由新建")
    public ResponseDTO<Object> appRouteCreate(@ApiParam("应用记录ID") @PathVariable("id") String id, @Validated @RequestBody AppRouteCreateParams params){
        // 获取应用信息
        AuthApp app = appService.getOneUnwrap(id);
        String appId = app.getAppId();
        String appName = app.getAppName();
        // 判断是否存在重复路由
        List<AuthAppRoute> routes = routeService.getByRoute(params.getRoute());
        if (!routes.isEmpty()){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,"存在重复路由信息");
        }
        AuthAppRoute route = new AuthAppRoute();
        BeanUtil.copyProperties(params, route,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        route.setAppId(appId);
        route.setAppName(appName);
        return ResponseDTO.succData(
                routeService.saveOne(route)
        );
    }

    @DeleteMapping("app/routes/{routeId}")
    @ApiOperation(value = "应用路由删除")
    public ResponseDTO<Object> appRouteDelete(@ApiParam("路由记录ID") @PathVariable("routeId") Long routeId){
        // 删除路由信息
        routeService.deleteOne(routeId);
        return ResponseDTO.succMsg("删除成功");
    }

    @PutMapping("app/routes")
    @ApiOperation(value = "应用路由更新")
    public ResponseDTO<Object> appRouteUpdate(@Validated @RequestBody AppRouteUpdateParams params){
        Long routeId = params.getId();
        // 获取路由信息
        AuthAppRoute route = routeService.getOneUnwrap(routeId);
        // 判断是否存在路由信息
        List<AuthAppRoute> routes = routeService.getByRoute(params.getRoute());
        // 为空不重复
        if (routes.isEmpty()){
            BeanUtil.copyProperties(params, route,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
            return ResponseDTO.succData(
                    routeService.updateOne(route)
            );
        }else {
            AuthAppRoute firstRoute = routes.get(0);
            // 是当前更新的记录
            if (firstRoute.getId().equals(route.getId())){
                BeanUtil.copyProperties(params, route,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
                return ResponseDTO.succData(
                        routeService.updateOne(route)
                );
            }else {
                return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,"存在重复路由信息");
            }
        }
    }

    @GetMapping("apps/{id}/routes")
    @ApiOperation(value = "应用路由列表")
    public ResponseDTO<Object> appRoutesList(@ApiParam("应用记录ID") @PathVariable("id") String id){
        // 获取应用信息
        AuthApp app = appService.getOneUnwrap(id);
        String appId = app.getAppId();
        String appName = app.getAppName();
        List<AuthAppRoute> routes = routeService.getByAppId(appId);
        return ResponseDTO.succData(routes);
    }
}
